package com.dev.liveshow.ui.activity;


import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import com.dev.liveshow.R;
import com.dev.liveshow.constant.Constants;
import com.dev.liveshow.databinding.ActivityAnchorBinding;
import com.google.common.util.concurrent.ListenableFuture;

import org.json.JSONObject;

import im.zego.zegoexpress.ZegoExpressEngine;
import im.zego.zegoexpress.callback.IZegoEventHandler;
import im.zego.zegoexpress.constants.ZegoPublisherState;
import im.zego.zegoexpress.constants.ZegoRoomState;
import im.zego.zegoexpress.constants.ZegoScenario;
import im.zego.zegoexpress.entity.ZegoCanvas;

public class AnchorActivity extends AppCompatActivity {

    private ActivityAnchorBinding binding;
    private String roomName;
    private ZegoExpressEngine engine;
    private boolean isMike; // 麦克风是否开启
    private boolean isCamera; // 摄像头是否开启
    private static final int PERMISSION_CODE = 101;
    private ZegoCanvas canvas;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_anchor);
        initData();
    }


    @SuppressLint("ResourceAsColor")
    private void initData() {
        Intent intent = getIntent();
        roomName = intent.getStringExtra("roomName");
        initLiveRoom();
        boolean isRequest = checkOrRequestPermission(PERMISSION_CODE);
        if (isRequest) {
            Toast.makeText(this,"权限已开启",Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this,"权限未请求",Toast.LENGTH_SHORT).show();
        }

        binding.btnMike.setOnClickListener(v -> {
            if (isMike) {
                engine.enableCamera(true);
            } else {
                isMike = true;
                engine.enableCamera(false);
            }
        });

        binding.btnMike.setOnClickListener(v -> {
            if (isMike) {
                isMike = false;
                Toast.makeText(this,"打开麦克风",Toast.LENGTH_SHORT).show();
                binding.btnMike.setImageResource(R.mipmap.mike_nor);
                engine.enableAudioCaptureDevice(true);
            } else {
                isMike = true;
                Toast.makeText(this,"关闭麦克风",Toast.LENGTH_SHORT).show();
                binding.btnMike.setImageResource(R.mipmap.mike_sel);
                engine.enableAudioCaptureDevice(false);
            }
        });

        binding.btnCamera.setOnClickListener(v -> {
            if (isCamera) {
                isCamera = false;
                Toast.makeText(this,"打开摄像头",Toast.LENGTH_SHORT).show();
                binding.btnCamera.setImageResource(R.mipmap.camera_nor);
                engine.enableCamera(true);
            } else {
                isCamera = true;
                Toast.makeText(this,"关闭摄像头",Toast.LENGTH_SHORT).show();
                binding.btnCamera.setImageResource(R.mipmap.camera_sel);
                engine.enableCamera(false);
                binding.anchorLayout.setBackgroundColor(R.color.colorPrimary);
            }
        });

    }

    /**
     * 初始化直播间
     */
    private void initLiveRoom() {
        engine = ZegoExpressEngine.createEngine(Constants.AppId, Constants.AppSign, true, ZegoScenario.LIVE, getApplication(), null);
        canvas = new ZegoCanvas(binding.anchorView);
        // 开启预览接口
        engine.startPreview(canvas);
        // 开启摄像头
        engine.enableCamera(true);
        // 开启麦克风
        engine.enableAudioCaptureDevice(true);
        engine.setEventHandler(new IZegoEventHandler() {
            @Override
            public void onRoomStateUpdate(String roomID, ZegoRoomState state, int errorCode, JSONObject extendedData) {
                super.onRoomStateUpdate(roomID, state, errorCode, extendedData);
            }

            @Override
            public void onPublisherStateUpdate(String streamID, ZegoPublisherState state, int errorCode, JSONObject extendedData) {
                super.onPublisherStateUpdate(streamID, state, errorCode, extendedData);
                if (errorCode == 0) {
                    Toast.makeText(AnchorActivity.this,"推流成功",Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(AnchorActivity.this,"推流失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    // 需要申请 麦克风权限-读写sd卡权限-摄像头权限
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.CAMERA",
            "android.permission.RECORD_AUDIO"};

    /**
     * 校验并请求权限
     */
    public boolean checkOrRequestPermission(int code) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, "android.permission.CAMERA") != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, "android.permission.RECORD_AUDIO") != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(PERMISSIONS_STORAGE,code);
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        // 停止所有的推流和拉流后，才能执行 logoutRoom
        engine.stopPreview();
        engine.setEventHandler(null);
        engine.stopPublishingStream();
        ZegoExpressEngine.destroyEngine(null);
        super.onDestroy();
    }
}